package cn.cosmosx.base.security.filter;

import cn.cosmosx.base.constant.AuthSwitch;
import cn.cosmosx.base.constant.GlobalConstant;
import cn.cosmosx.base.constant.ResultCode;
import cn.cosmosx.base.encrypt.aes.AESUtil;
import cn.cosmosx.base.encrypt.jwt.JWTsUtil;
import cn.cosmosx.base.helper.SessionHelper;
import cn.cosmosx.base.security.entity.SecurityUserVo;
import cn.cosmosx.base.security.service.CacheProviderService;
import cn.cosmosx.base.util.CookieUtils;
import cn.cosmosx.base.util.ResponseUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.stream.Collectors;

/**
 * SpringSecurity认证过滤器
 */
@Component
public class JWTAuthenticationFilter extends OncePerRequestFilter {
    @Autowired
    private CacheProviderService cacheProviderService;

    @Override
    protected void doFilterInternal(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain filterChain) throws ServletException, IOException {
        // 白名单无需认证，放行
        if (AuthSwitch.matchWhiteList(request)) {
            filterChain.doFilter(request, response);
            return;
        }
        // 拿到请求头token 并校验
        String token = request.getHeader(GlobalConstant.TOKEN);
        if (StringUtils.isEmpty(token)) {
            token = CookieUtils.getToken(request);
        }
        if (StringUtils.isEmpty(token)) {
            ResponseUtils.wrapResponse(response, ResultCode.E00005);
            return;
        }
        token = AESUtil.decrypt(token);
        try {
            JWTsUtil.parseJwt(token);
        } catch (Exception e) {
            ResponseUtils.wrapResponse(response, ResultCode.E00003);
            return;
        }
        // 拿到缓存Redis Session
        SecurityUserVo session = cacheProviderService.getToken(token);
        if (session == null) {
            ResponseUtils.wrapResponse(response, ResultCode.E00004);
            return;
        }
        // 调用SpringSecurity进行认证，关键信息是UsernamePasswordAuthenticationToken中调用设置了已登录鉴权super.setAuthenticated(true);
        SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(
                session.getUsername(),
                session.getPassword(),
                session.getRoles().stream().map(SimpleGrantedAuthority::new)
                        .collect(Collectors.toSet())
        ));
        //存 session 到本地线程中
        SessionHelper.put(session);
        filterChain.doFilter(request, response);
    }
}
